TcpChannelResolver = class("TcpChannelResolver");
function TcpChannelResolver:ctor(_tcp)
    self.tcpChannel = _tcp

    local addEvent = function(action,func)
        if action then
            return  action + func
        else
            return func
        end
    end
    self.tcpChannel.OnConnectFinish =addEvent(self.tcpChannel.OnConnectFinish,function(_succ) self:OnConnectFinish(_succ) end);
    self.tcpChannel.OnDisconnect =addEvent(self.tcpChannel.OnDisconnect,function() self:OnDisconnect() end);
    self.tcpChannel.OnRevData =addEvent(self.tcpChannel.OnRevData,handler(self, self.OnRevData));

    self.onRecvCallback = {}
    self.pingRecvTime = 0
end

function TcpChannelResolver:Connect(host, port)
    self.tcpChannel:Connect(host, port);
end

function TcpChannelResolver:TcpClose()
    self.tcpChannel:Close();
end

function TcpChannelResolver:OnConnectFinish(succ)
    if succ then
        EVTM.dispatch(EVENT.SYS_TCP_CONNECT_FINISH)
    else
        EVTM.dispatch(EVENT.SYS_TCP_DISCONNECTED)
    end
end

function TcpChannelResolver:OnDisconnect()
    EVTM.dispatch(EVENT.SYS_TCP_DISCONNECTED)
end

function TcpChannelResolver:Send(msgID, bytes)
    local gameProtocol = GameMessage.Protocol()
    gameProtocol.messageType = msgID
    gameProtocol.code = ResponseCode.SUCCESS
    gameProtocol.data = bytes
    self.tcpChannel:Send(gameProtocol:SerializeToString())
end

function TcpChannelResolver:OnRevData(bytes)
    for _, callback in pairs(self.onRecvCallback) do
        callback()
    end
    self.pingRecvTime = 0

    local msg = GameMessage.Protocol()
    msg:ParseFromString(bytes)
    local msgID = msg.messageType
    local code = msg.code
    --print('##########################Recv##########################',msgID, code, msg.data)
    if msgID == MsgType.PING then
        self:Send(MsgType.PING, '')
    end

    if code == ResponseCode.FAILED then
        EVTM.dispatch(EVENT.SYS_TCP_RECEIVE_ERR..tostring(msgID), code)
        --logError('####################ErrorCode####################### ' .. tostring(code))
    else
        EVTM.dispatch(EVENT.SYS_TCP_RECEIVE_MSG..tostring(msgID), {msg.data})
    end
end
